<template>
  <div id="FForm">
    <h3
      v-if="title"
      :style="{ width: width + 'px', fontSize: titleFontSize + 'px' }"
      :class="{ center: center }"
    >
      {{ title }}
    </h3>
    <div
      class="Fform-table"
      :class="{ center: center }"
      :style="{ width: width + 'px' }"
    >
      <div
        class="Fform-table-item"
        v-for="(item, index) in data"
        :key="index"
        :class="{ long: item.long }"
      >
        <label
          :style="{
            background: background,
            color: color,
            fontSize: fontSize + 'px',
          }"
          >{{ item.label }}</label
        >
        <!-- 插槽内容 -->
        <div class="form-item form-item-slot" v-if="item.type === 'slot'">
          <slot name="aSlot"></slot>
        </div>
        <el-input
          v-model="form[item.name]"
          :placeholder="item.placeholder ? item.placeholder : '请输入内容'"
          v-if="item.type === 'input'"
          class="form-item-input form-item"
          :disabled="readonly"
        ></el-input>
        <el-select
          v-model="form[item.name]"
          :placeholder="item.placeholder ? item.placeholder : '请选择内容'"
          v-if="item.type === 'option'"
          class="form-item-option form-item"
          :disabled="readonly"
        >
          <el-option
            v-for="(options, index) in item.options"
            :key="index"
            :label="options.label"
            :value="options.value"
          >
          </el-option>
        </el-select>
        <el-date-picker
          :disabled="readonly"
          class="form-item-date form-item"
          v-model="form[item.name]"
          type="date"
          :placeholder="item.placeholder ? item.placeholder : '请选择日期'"
          :editable="false"
          v-if="item.type === 'date'"
          format="yyyy 年 MM 月 dd 日"
          value-format="yyyy-MM-dd"
        >
        </el-date-picker>
        <el-upload
          accept=".jpg,.jpeg,.gif,.png,.bmp"
          ref="upload"
          class="upload-demo"
          action="sdf"
          list-type="picture-card"
          :file-list="fileList[item.name]"
          :auto-upload="false"
          :on-remove="(file) => removefile(file, item.name)"
          :on-change="(file, fileList) => changefile(file, fileList, item.name)"
          :limit="1"
          v-if="item.type === 'upload'"
          :disabled="readonly"
        >
          <button
            style="margin-right: 0px; padding: 5px 6px; letter-spacing: 0px"
            type="button"
            class="btn-linesave picture"
            slot="trigger"
            v-if="fileButtonHide"
          >
            <span>点击上传图片 </span>
          </button>
        </el-upload>
      </div>
    </div>
  </div>
</template>

<script>
//组件介绍：
//===============================
/**
 * 1.一个样式的表单组件
 * 2.按照对应格式进行填写data
 * 3.可设置的属性
 * - data => 基本表单模型， Array
 *    - type =>  option/input/date（日期选择器）类型
 *    - option => 需要有options选择列表 => [{label:xxx;value:xxx}] Array
 *    - label => 表单项名称 String
 *    - default => 默认填写的内容 String // 日期选择器需要传递Date实例
 *    - placeholder => 默认placeholder String
 *    - name => 表单对应的key String
 * 4.事件 formChange => 表单内容改变时触发 Methods
 * 5.readonly => 整个表单是否只读 Boolean
 * 6.label的fontSize,color,background可选属性 String
 * 7.width 表单宽度 String
 * 8.center 表单是否居中 String
 * 9.title 表单的title Array
 */

//========================
export default {
  name: 'FForm',
  props: {
    data: {
      type: Array,
      required: true,
    },
    fileButtonHide: {
      type: Boolean,
      default: true,
    },
    title: {
      type: String,
    },
    titleFontSize: {
      type: String,
      default: '20',
    },
    readonly: {
      type: Boolean,
      default: false,
    },
    center: {
      type: Boolean,
      default: true,
    },
    width: {
      type: String,
      default: '890',
    },
    background: {
      type: String,
      default: '#d2eaff',
    },
    color: {
      type: String,
      default: '#000',
    },
    fontSize: {
      type: String,
      default: '13',
    },
    fileList: {
      type: Object,
    },
  },
  data() {
    return {
      form: {},
      // fileList: {},
    };
  },
  methods: {
    //获取base64
    dataURLtoFile(dataurl, filename) {
      var arr = dataurl.split(','),
        mime = arr[0].match(/:(.*?);/)[1],
        bstr = atob(arr[1]),
        n = bstr.length,
        u8arr = new Uint8Array(n);
      while (n--) {
        u8arr[n] = bstr.charCodeAt(n);
      }
      return new File([u8arr], filename, {
        type: mime,
      });
    },
    imgToBase64(url, cb) {
      var canvas = document.createElement('canvas'),
        ctx = canvas.getContext('2d'),
        img = new Image();

      img.crossOrigin = 'Anonymous';
      img.onload = function () {
        canvas.height = img.height;
        canvas.width = img.width;
        ctx.drawImage(img, 0, 0);
        var dataURL = canvas.toDataURL('image/png');
        cb && cb(dataURL);
        canvas = null;
      };
      img.src = url;
    },
    //初始化表单
    init() {
      this.data.forEach((item) => {
        if (item.type === 'upload') {
          this.$set(this.form, item.name, '');
        } else {
          this.$set(this.form, item.name, item.default);
        }
      });
    },
    //改变图片的钩子
    async changefile(file, fileList, name) {
      console.log(file.raw);
      this.$set(this.form, name, file.raw);
    },
    //删除图片的钩子
    removefile(file, name) {
      // const fileIndex = this.form[name].findIndex(
      //   (item) => item.name === file.name
      // );
      // this.form[name].splice(fileIndex, 1);
      this.$set(this.form, name, '');
    },
  },
  created() {
    this.init();
  },

  watch: {
    //表单内容改变进行发送表单
    form: {
      //表单改变重新返回
      handler(val) {
        this.$emit('formChange', val);
      },
      deep: true,
    },
    readonly(val) {
      if (val) {
        //只读之后清除上传列表
        if (this.$refs.upload) {
          this.$refs.upload.forEach((item) => {
            item.clearFiles();
          });
        }
      }
    },
  },
};
</script>

<style lang="less" scoped>
#FForm {
  h3 {
    line-height: 1em;
  }
  .upload-demo {
    display: flex;
    justify-content: flex-start;
    align-items: center;
    padding: 12px;
    box-sizing: border-box;
    background: #fff;
    &.disabled {
      background-color: #f5f7fa;
    }
    &::v-deep .el-upload-list__item {
      margin: 0;
    }
    &::v-deep .el-upload-list__item {
      width: 223px;
      height: 129px;
      object-fit: cover;
      border: none;
    }
    &::v-deep .el-upload--text {
      flex: 0 0 93px;
    }
    &::v-deep .el-upload-list__item {
      transition: none !important;
      // margin: 0;
    }
    &::v-deep .el-upload-list {
      line-height: 0;
    }
    &::v-deep .el-upload {
      border: none;
      background: #fff;
      height: 129px;
    }
  }
  .Fform-table {
    display: flex;
    flex-wrap: wrap;
    border: 1px solid #71b3d6;
    border-bottom: none;
    border-right: none;

    .Fform-table-item {
      width: 50%;
      box-sizing: border-box;
      display: table;
      border-bottom: 1px solid #71b3d6;
      border-right: 1px solid #71b3d6;
      min-height: 50px;
      position: relative;
      &.long {
        width: 100%;
      }

      .form-item {
        position: absolute;
        top: 0;
        width: calc(100% - 124px);
        bottom: 0;
        display: flex;
        flex-direction: column;
      }
      .form-item-slot {
        text-align: left;
        line-height: 50px;
        padding: 0 15px;
      }
      label {
        display: table-cell;
        vertical-align: middle;
        box-sizing: border-box;
        width: 124px;
        min-height: 100px;
        background: #d2eaff;
        border-right: 1px solid #71b3d6;
        text-align: center;
      }
    }
    &::v-deep .el-input__inner {
      border: none;
      flex: 1;
    }
    &::v-deep .el-input {
      flex: 1;
      display: flex;
      flex-direction: column;
    }
    .form-item-date {
      &::v-deep .el-input__inner {
        padding-left: 15px;
        cursor: pointer;
      }
      &::v-deep .el-icon-date {
        display: none;
      }
    }
    &.center {
      margin: 0 auto;
    }
  }
  .center {
    margin: 15px auto;
  }
}
</style>
